package com.example.toolproject.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.toolproject.demo.domain.User;
import com.example.toolproject.demo.domain.UserDataSearch;
import com.example.toolproject.demo.service.UserDataSearchService;
import com.example.toolproject.demo.util.ResultBean;
import com.example.toolproject.demo.util.jwt.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName UserDataSearchController
 * @Description TODO
 * @Author lvyongwei
 * @Date 2020-06-29 15:02
 **/
@Controller
@CrossOrigin
@RequestMapping("/userDataSearch")
public class UserDataSearchController {

    @Autowired
    private UserDataSearchService userDataSearchService;

    private Logger logger= LoggerFactory.getLogger(UserDataSearchController.class);

    /**
     * 用户引用数据
     * @param request
     * @param array
     * @return
     */
    @PostMapping("/referenceData")
    @ResponseBody
    public ResultBean referenceData(HttpServletRequest request, @RequestBody String array){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        /**
         * 获取用户id
         */
        int userId=u.getId();
        /**
         * 解析json数组数据
         */
        JSONObject jsonObject=JSONObject.parseObject(array);
        /**
         * 去掉两端的括号
         */
        String str=jsonObject.getString("dataSearchIds");
        String dataSearchIds=str.substring(1,str.length()-1);
        /**
         * 分割逗号为数组
         */
        List<String> list= new ArrayList<>(Arrays.asList(dataSearchIds.split(",")));
        /**
         * 判断数据库表有此数据，去除
         */
        for(int i=0;i<list.size();i++){
            //调用方法判断是否存在
            UserDataSearch userDataSearch=userDataSearchService.ifExist(userId,Long.valueOf(list.get(i)));
            if(!StringUtils.isEmpty(userDataSearch) || userDataSearch!=null){
                list.remove(i);
                //去掉重复的后，list长度减小
                i--;
            }
        }
        try{
            userDataSearchService.referenceData(list,userId);
            return ResultBean.success("引用成功");
        }catch (Exception e){
            logger.error("引用数据添加错误");
            return ResultBean.error("引用失败");
        }
    }


    /**
     * 用戶取消引用數據
     * @param request
     * @param array
     * @return
     */
    @PostMapping("/cancelReference")
    @ResponseBody
    public ResultBean cancelReference(HttpServletRequest request, @RequestBody String array){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        /**
         * 获取用户id
         */
        int userId=u.getId();
        /**
         * 解析json数组数据
         */
        JSONObject jsonObject=JSONObject.parseObject(array);
        /**
         * 去掉两端的括号
         */
        String str=jsonObject.getString("dataSearchIds");
        String dataSearchIds=str.substring(1,str.length()-1);
        /**
         * 分割逗号为数组
         */
        List<String> list= Arrays.asList(dataSearchIds.split(","));
        try{
            userDataSearchService.cancelReference(list,userId);
            return ResultBean.success("取消引用成功");
        }catch (Exception e){
            logger.error("取消引用数据错误");
            return ResultBean.error("取消引用失败");
        }
    }
}
